/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.teama;

import java.io.IOException;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 *
 * @author bamidei
 */
@WebServlet(name = "Email", urlPatterns = {"/Email"})
public class Email extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        boolean emailSuccess = false;

        int issue_id = Integer.parseInt(request.getParameter("id"));
        Issue activeIssue = IssueListDA.getIssue(issue_id);
                 
        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", "localhost");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress("BugTracker@nomail.com"));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(activeIssue.getSubmitByEmail()));
            // Don't add if not assigned
            if(!activeIssue.getAssignToEmail().equals("not_assigned@null.com")){
               message.addRecipient(Message.RecipientType.TO,
                     new InternetAddress(activeIssue.getAssignToEmail()));
            }

            // Set Subject: header field
            message.setSubject("Issue# "+issue_id+" Status update for "+activeIssue.getAppName());

            // Now set the actual message
            message.setText("Current Status: "+activeIssue.getAppName()+" Ver. "+activeIssue.getAppVersion()+" \n"+                  
                            activeIssue.getIssueSummary()+" "+activeIssue.getIssueDesc()+"\n"+
                            activeIssue.getCreatedDate() +" "+activeIssue.getPriorityLabel()+" "+
                            activeIssue.getStatus()+" "+activeIssue.getAssignToName());          

            // Send message
            Transport.send(message);
            System.out.println("Email sent successfully....");
            emailSuccess = true;
        } catch (MessagingException mex) {
            emailSuccess = false;
        }

        if (!emailSuccess) {
            request.setAttribute("error", "Failure to send emails.");
        } else {
            request.setAttribute("msg", "Status email sent successfully.");
        }
        //Forward to JSP
        RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/getIssueList");
        dispatcher.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
